package com.scm.erp.framework.threadevent;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scm.erp.framework.pojo.netWorkImages;
import com.scm.erp.framework.repository.netWorkImagesRepository;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 此类只负责数据的图片更新  可用但是性能偏差
 * */
@Component
public class getUrlImages {
    private final static Logger logger = LoggerFactory.getLogger(getUrlImages.class);
    @Resource
    private netWorkImagesRepository imagesRepository;
    private List<String> classList = new ArrayList();
    private Document document;
    private Document documentJsons;
    private int pg = 0;
    private boolean flags =false;
    private Boolean isStop=false;

    public Boolean getStop() {
        return isStop;
    }

    public void setStop(Boolean stop) {
        isStop = stop;
    }

    /**
     * 导航分类
     * */
    private List<String> getCLassClassify(){
        try {
            document = Jsoup.connect("https://jixianci.fkdmg.com/bizhis/index/views.html").timeout(200000).get();
        }catch (Exception e){
            logger.error("在getCLassClassify 类中 IO异常");
        }
       Elements elementsClass = document.getElementsByClass("jkbz-nav");
        int taGre = elementsClass.size();
        if(taGre > 0){
            Element frame = elementsClass.get(0);
            Elements ul = frame.select("ul");
            Elements li = ul.select("li");
            if(li.is("ul")==false){
                Elements a = li.select("a");
                for (Element alink:a) {
                    classList.add(alink.attr("href"));
                }
            }else {
                Elements ulTow = li.select("ul");
                Elements liTow = ulTow.select("li");
                Elements a = liTow.select("a");
                for (Element alink:a) {
                    classList.add(alink.attr("href"));
                }
            }
        }
        return classList;
    }
//    https://jixianci.fkdmg.com/bizhis/index/views.html?isget=1&pg=2
    /**
     *枚举图片地址
     * */
    public void getUrlImages(){
        List<String> listClassIfy = getCLassClassify();
        if(listClassIfy.size()>0){
            for (int classIfyId = 1;classIfyId <listClassIfy.size();classIfyId++ ){
                if(getStop()==false){
                    String allURLAddress = listClassIfy.get(0) + listClassIfy.get(classIfyId);
                    /**
                     * 根据最大的数据进行迭代更新
                     * */
                    String isMaxNClassNavigation = imagesRepository.findMaxNClassNavigation();
                    String isMaxNClassNPage = imagesRepository.findMaxNClassNPage();
                    pg=1;
                    if(allURLAddress.equals(isMaxNClassNavigation)==true && isMaxNClassNavigation  !=null){
                        pg = Integer.parseInt(isMaxNClassNPage);
                        if(flags==true){
                            if(allURLAddress.equals(imagesRepository.findMaxNClassNavigation())==false){
                                flags=false;
                                pg=1;
                            }
                        }
                    }
                    indexImg(allURLAddress);
                }else {
                    break;
                }
            }
        }
    }
    public void indexImg(String allURLAddress){
        for (;;pg++){
            if(getStop()==false){
                try {
                    documentJsons = Jsoup.connect(allURLAddress + "?isget=1&pg="+pg).timeout(200000).ignoreContentType(true).get();
                }catch (Exception e){
                    e.printStackTrace();
                }
                String jsonValues = documentJsons.body().text();
                if (jsonValues.equals("[]")==true){
                    flags=true;
                    break;
                }
                JSONArray jsonFkDmgBanJson = JSONObject.parseArray(jsonValues);
                for (int jsonImg=0;jsonImg < jsonFkDmgBanJson.size();jsonImg++){
                    if(getStop()==false){
                        /**
                         * 估算这里的异常问题是在这里被生产，上面捕获到数据这里JSON数据出现指针为空无法使用
                         * */
                        String isJsonDat = jsonFkDmgBanJson.get(jsonImg).toString();
                        JSONObject JsonFkDmgBanJson = JSONObject.parseObject(isJsonDat);
                        if(JsonFkDmgBanJson.isEmpty()==false){
                            String url = (String) JsonFkDmgBanJson.get("url");
                            String category= (String) JsonFkDmgBanJson.get("category");
                            String isNImagesUrl = imagesRepository.findByNImagesUrl(url);
                            if(!url.equals(isNImagesUrl)){
                                netWorkImages images = new netWorkImages();
                                images.setT_Ncategory(category);
                                images.setT_NClassNavigation(allURLAddress);
                                images.setT_NImagesUrl(url);
                                images.setT_NPages(String.valueOf(pg));
                                imagesRepository.save(images);
                            }else {
                                netWorkImages images = new netWorkImages();
                                images.setT_Ncategory(category);
                                images.setT_NClassNavigation(allURLAddress);
                                images.setT_NImagesUrl(url);
                                images.setT_NPages(String.valueOf(pg));
                                images.setT_NID(imagesRepository.findById(isNImagesUrl));
                                imagesRepository.save(images);
                                System.out.println(Thread.currentThread().getName() + "========更新数据！");
                            }
                        }
                    }else {
                        break;
                    }
                }
            }else {
                break;
            }
        }
    }

    /**
     * 过滤数据库中所有的值是否存在404问题
     * */
    public void dbIsImgUrl(){
        List<netWorkImages> netWorkImagesList = imagesRepository.findAll();
        for (int i=0;i<netWorkImagesList.size();i++){
           String addresses = netWorkImagesList.get(i).getT_NImagesUrl();
            try {
                URL url = new URL(addresses);
                HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
                urlConnection.setRequestMethod ("HEAD");
                urlConnection.setConnectTimeout(5000); //视情况设置超时时间
                urlConnection.connect();
                if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND){
                    imagesRepository.deleteById(netWorkImagesList.get(i).getT_NID());
                    System.out.println("存在一条404数据实行删除策略" + netWorkImagesList.get(i).getT_NImagesUrl());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
